package cn.caojun.auth.service.Impl;


import cn.caojun.auth.dto.LoginDTO;
import cn.caojun.auth.service.ILoginService;
import cn.caojun.basic.utils.BasicMap;
import cn.caojun.org.domain.Employee;
import cn.caojun.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        //1.参数非空校验
        if (StringUtils.isEmpty(loginDTO.getUsername())||StringUtils.isEmpty(loginDTO.getPassword())){
            throw new RuntimeException("用户名或密码不能为空");
        }
        //2.根据用户名查询信息
        String username=loginDTO.getUsername();
        Employee employee=employeeMapper.loadByUsername(username);

        //3.如果员工为空，返回错误信息
        if (Objects.isNull(employee)){
            throw new RuntimeException("用户名或密码错误！请重新输入");
        }
        //4.如果不为空，进行对比
        //4.1.如果密码实效，返回错误信息
        if (!loginDTO.getPassword().equals(employee.getPassword())){
            throw new RuntimeException("密码错误请重新输入");
        }
        //4.2.如果密码一致则登陆成功
        Map<String,Object> map=new HashMap<>();
        //5.将员工信息存入前端，用户展示用户名等信息
        map.put("loginUser",employee);
        //6.将token和对应的员工信息存入LoginConstant常量类
        String token= UUID.randomUUID().toString();
        BasicMap.loginMap.put(token,employee);
        employee.setPassword("");
        //7.将token返回前端，用于后续判断拦截登录时用户是否登录
        map.put("token",token);
        return map;
    }
}
